<?php
namespace app\api\controller;

use app\api\model\Bank;
use app\api\model\Configs;
use app\api\model\User;
use app\api\model\UserAlipay;
use app\api\model\UserBank;
use app\api\model\UserScoreLog;

class UserScore extends Base
{
    // 不需要验证
    protected $excludeValidateCheck = [
        'information', 'transfersInformation', 'logs',
    ];

    protected $autoNewModel = false;// 是否自动实例化当前模型
    // 定义自动实例化模型
//    protected $ModelPath = 'UserScoreLog';

    public function information(){
        $userId = request()->UserModel->id;
        $infos = User::where('id', $userId)->find();
        $parentInfos = User::where('id', $infos['pid'])->find();
//        $inviteStatus = true;
//        if(empty($parentInfos)){
//            $parentInfos['id'] = '';
//            $parentInfos['phone'] = '';
//            $inviteStatus = false;
//        }
//        $count = \app\api\model\User::where('pid', $userId)->count();
        $configs = Configs::column('content', 'alias');
        $is_open_withdrawal = $configs['IS_OPEN_WITHDRAWAL'];

        //整理数据
        $data = [
            'main_title'=>'我的积分',
            'background'=>get_oss_url('/static/teams-bg.png'),
            'infos'=>[
                'avatar'=>get_oss_url('/static/logo.png'),
                'nickname'=>$infos['phone'],
                'rows'=>[
                    'ID：' . $infos['id'],
                    '手机号码：' . $infos['phone'],
                    '邀请码：' . $infos['invite_code'],
                ],
                'level_name'=>'普通会员',
                'idents'=>[],
                'qr'=>[
                    'enable'=>true,
                    'text'=>'',
                    'alias'=>'none',
                    'params'=>[],
                ],
            ],
            'statistics'=> [
                'enable'=>true,
                'lists'=>[
                    [
                        'name'=>'总资产(元)',
                        'text'=>calc_amount($infos['score']),
                        'alias'=>'wallets.index',
                        'params'=>[
//                            'alias'=>'balance'
                        ],
                    ],
//                    [
//                        'name'=>'消费积分',
//                        'text'=>$infos['integral'] / 100,
//                        'alias'=>'account.wallets.logs',
//                        'params'=>[
//                            'alias'=>'integral'
//                        ],
//                    ],
//                    [
//                        'name'=>'绿色积分',
//                        'text'=>$green_points / 100,
//                        'alias'=>'account.wallets.logs',
//                        'params'=>[
//                            'alias'=>'green_points'
//                        ],
//                    ],

                ]
            ],
            'tools'=> [
                'enable'=>true,
                'lists'=>[
                    [
                        'name'=>'账单记录',
                        'class'=>'icon-order',
                        'alias'=>'user_score.logs',
                        'params'=>[
//                            'alias'=>'balance'
                        ],
                    ],
//                    [
//                        'name'=>'转账记录',
//                        'class'=>'icon-transfer-pay',
//                        'alias'=>'wallets.index',
//                        'params'=>[
//
//                        ],
//                    ],

                ]
            ],
            'formData'=>[],
            'sections'=>[
                'amounts'=>[
                    'enable'=>true,
                    'lists'=>[
                        [
                            'img'=>get_oss_url('/static/system/account/wallets/wallets-icon1.png'),
                            'title'=>'可用积分',
                            'amount'=>0,
                            'alias'=>'none',
                            'params'=>[],
                        ],
                    ]
                ],
                'tools'=>[
                    'enable'=>true,
                    'transfer'=>[
                        'enable'=>false,
                        'username'=>'',
                        'type'=>'',
                        'name'=>'接收转账用户',
                        'placeholder'=>'请输入接收用户的手机号码',
                        'button'=>'立即转账',
                    ],
                    'lists'=>[
                        [
                            'action'=>'transfer',
                            'img'=>get_local_url('/static/system/account/wallets/wallets-icon3.png'),
                            'name'=>'转账',
                            'amount'=>0,
                            'alias'=>'',
                            'params'=>[],
                            'enable'=>true,
                        ],
                        [
                            'action'=>'',
                            'img'=>get_local_url('/static/system/account/wallets/wallets-icon4.png'),
                            'name'=>'兑换',
                            'amount'=>0,
                            'alias'=>'user_score.withdrawals',
                            'params'=>[],
                            'enable'=>($is_open_withdrawal == 'on' ? true : false),
                        ],
//                        [
//                            'action'=>'',
//                            'img'=>get_oss_url('/static/system/accounts/wallets/wallets-icon5.png'),
//                            'name'=>'交易明细',
//                            'amount'=>0,
//                            'alias'=>'account.wallets.logs',
//                            'params'=>[
//                                'alias'=>'balance'
//                            ],
//                            'enable'=>true,
//                        ],
                    ]
                ],
                'properties'=>[
                    'enable'=>false,
                    'lists'=>[
                        [
                            'action'=>'',
                            'img'=>get_oss_url('/static/logos/ysyp.png'),
                            'name'=>'',
                            'desc'=>'',
                            'amount'=>0,
                            'tip'=>'',
                            'alias'=>'none',
                            'params'=>[],
                        ],
                    ]
                ],
            ],
//            'search'=>[
//                'enable'=>false,
//                'placeholder'=>'',
//                'button'=>'',
//            ],
//            'ad'=>false,
//            'invite'=>[
//                'enable'=>$inviteStatus,
//                'title'=>'我的邀请人',
//                'nickname'=>'ID：' . $parentInfos['id'],
//                'mobile'=>$parentInfos['phone'],
//            ],
//            'counts'=>[
//                'enable'=>true,
//                'lists'=>[
//                    [
//                        'name'=>'直推人数',
//                        'count'=>$count,
//                        'type'=>'',
//                    ]
//                ],
//            ],
//            'lists'=>[
//                'enable'=>true,
//                'title'=>'',
//                'filters'=>[
//                    'type'=>'',
//                    'search_keyword'=>'',
//                    'page'=>1,
//                ]
//            ]
        ];
        //响应数据
        return showSuccess($data);
    }

    public function transferInformation(){
        $userId = request()->UserModel->id;
        $transferPhone = request()->param('username', 0);
        $infos = User::where('id', $userId)->find();
        if($transferUser = User::where('phone', $transferPhone)->find())
        {
            $type = 'score';
            //整理数据
            $data = [
                'main_title'=>'积分转账',
                'account'=> [
                    'account_id'=>$infos['id'],
                    'mobile'=>$infos['phone'],
                    'nickname'=>$infos['phone'],
                    'avatar'=>get_oss_url('/static/logo.png'),
                ],
                'transfer_account'=> [
                    'account_id'=>$transferUser['id'],
                    'mobile'=>$transferUser['phone'],
                    'nickname'=>$transferUser['phone'],
                    'avatar'=>get_oss_url('/static/logo.png'),
                ],
                'texts'=> [
                    'transfer_amount'=>'可转：' . calc_amount($infos['score']),
                    'transfer_input'=>[
                        'name'=>'转账金额',
                        'placeholder'=>'请输入金额',
                    ],
                    'transfer_tip'=>'预计接受金额',
                ],
                'tips'=> '',
                'formData'=>[
                    'amount'=>'',
                    'type'=>$type,
                    'username'=>$transferPhone,
                    'pay_password'=>'',
                    'user_id'=>$userId
                ],
                'amounts'=>[
                    'amount'=>'',
                    'rate'=>0,
                    'tax'=>0,
                    'arrival'=>'',
                    'need'=>'',
                ]
            ];
            //响应数据
            return showSuccess($data);
        }else{
            return showError('不存在该用户');
        }
    }

    public function transferAction(){
        $params = request()->param();
//        dd($params);
        $currentUser = request()->UserModel;
        $currentUserId = $currentUser->id;

        $toUserPhone = $params['username'];
        if($toUser = User::where('phone', $toUserPhone)->find())
        {
            $alias = request()->param('type');
            $amount = bcmul(request()->param('amount'), \app\model\Base::$hundred);

            $currentUserParentIds = $currentUser['parent_ids'];
            $toUserParentIds = $toUser['parent_ids'];
            if(strpos($currentUserParentIds, '|' . $toUser['id'] . '|') !== false || strpos($toUserParentIds, '|' . $currentUser['id'] . '|') !== false)
            {
                if($amount > $currentUser[$alias])
                {
                    return showError('可转账额度不足');
                }

                $type = 'score_transfer';
                $isDone = User::afterTransfer($currentUserId, $toUser['id'], $amount, $alias, $type);
                if($isDone === true){
                    return showSuccess([], '转账成功');
                }else{
                    return showError('转账失败');
                }
            }else{
                return showError('不在同一条线上');
            }
        }else{
            return showError('不存在该用户');
        }
    }

    public function withdrawalsInformation()
    {
        // 提现
        $userId = request()->UserModel->id;
//        $transferPhone = request()->param('username', 0);
        $infos = User::where('id', $userId)->find();
        $alias = 'score';
        $bankInfos = [

        ];
        $formData = [
            'type'=>'bank',
            'amount'=>'',
            'real_name'=>'',
            'card_no'=>'',
            'bank_name'=>'',

            'alipay_account'=>'',
            'alipay_real_name'=>'',

            'mobile'=>'',
            'id_card'=>'',
            'ecny_number'=>'',
            'pay_password'=>'',
            'user_id'=>$userId
        ];

        $currentIndex = 0;
        $error = false;
        if($userBankInfos = UserBank::where('user_id', $userId)->find()){
            $formData['real_name'] = $userBankInfos['real_name'];
            $formData['bank_name'] = $userBankInfos['bank_name'];
            $formData['card_no'] = $userBankInfos['card_no'];
            $currentIndex = Bank::where('guard_name', $userBankInfos['bank_name'])->value('id') - 1;
            $error = $userBankInfos['status'] == 'disabled' ? true : false;
        }
        $bankList = Bank::field('id, guard_name name')->whereNotNull('guard_name')->select();

        if($alipay_account = UserAlipay::where('user_id', $userId)->value('account'))
        {
            $formData['alipay_account'] = $alipay_account;
        }
        if($alipay_real_name = UserAlipay::where('user_id', $userId)->value('real_name'))
        {
            $formData['alipay_real_name'] = $alipay_real_name;
        }

        //整理数据
        $data = [
            'main_title'=>'兑换',
            'error'=>$error,
            'current_index' =>$currentIndex,
            'bank_list'=>[$bankList],
            'account'=>[
                'account_id'=>$infos['id'],
                'mobile'=>$infos['phone'],
                'nickname'=>$infos['phone'],
                'avatar'=>get_oss_url('/static/logo.png'),
                'amount'=>calc_amount($infos[$alias]),
                'text'=>'可兑换金额'
            ],
            'types'=>[
                [
                    'name'=>'银行卡',
                    'img'=>get_local_url('/static/system/account/wallets/withdrawals-icon1.png'),
                    'type'=>'bank',
                    'inputs'=>[
                        'bank_name',
                        'real_name',
                        'card_no'
                    ],
                ],
//                [
//                    'name'=>'支付宝',
//                    'img'=>get_local_url('/static/system/account/wallets/alipay.png'),
//                    'type'=>'alipay',
//                    'inputs'=>[
//                        'alipay_account',
//                        'alipay_real_name',
//                    ],
//                ]
            ],
            'formData'=>$formData,
            'inputs'=>[
                'amount'=>[
                    'name'=>'兑换金额',
                    'placeholder'=>'请输入您本次要提现的金额',
                    'type'=>'',
                ],
                'real_name'=>[
                    'name'=>'真实姓名',
                    'placeholder'=>'请输入您的真实姓名',
                    'type'=>'',
                ],
                'alipay_account'=>[
                    'name'=>'支付宝账号',
                    'placeholder'=>'请输入您的支付宝账号',
                    'type'=>'',
                ],
                'alipay_real_name'=>[
                    'name'=>'支付宝实名',
                    'placeholder'=>'请输入您的支付宝实名',
                    'type'=>'',
                ],
                'card_no'=>[
                    'name'=>'银行卡号',
                    'placeholder'=>'请输入您的收款卡号',
                    'type'=>'',
                ],
                'mobile'=>[
                    'name'=>'银行卡绑定手机',
                    'placeholder'=>'请输入您的银行卡绑定手机',
                    'type'=>'',
                ],
                'bank_name'=>[
                    'name'=>'开户行',
                    'placeholder'=>'请输入您的银行卡对应开户行',
                    'type'=>'',
                ],
                'id_card'=>[
                    'name'=>'',
                    'placeholder'=>'',
                    'type'=>'',
                ],
                'ecny_number'=>[
                    'name'=>'',
                    'placeholder'=>'',
                    'type'=>'',
                ],

            ],
            'amounts'=>[
                'amount'=>'',
                'rate'=>6,
                'tax'=>'',
                'arrival'=>'',
            ],
        ];
        //响应数据
        return showSuccess($data);
    }

    public function withdrawalsApply(){
//        $isOpen = Configs::where('alias', 'IS_OPEN_WITHDRAWAL')->value('content');
//        if($isOpen == 0){
//            return showError('兑换暂停');
//        }

        $timeH = date('H', time());
        if($timeH >= '05' && $timeH <= '24'){
            $userInfos = request()->UserModel;
//            if($userInfos['withdraw_switch'] == 'off'){
//                return showError('该账号禁止提现');
//            }
            $userId = request()->UserModel->id;
            $params = request()->param();
            $amount = bcmul_amount($params['amount']);
            $rate = 0.06;
            $rate_money = bcmul($amount, $rate);
            $real_money = bcadd($amount, $rate_money);
            if($userInfos['score'] < $real_money){
                return showError('余额不足');
            }

            $apply_type = request()->param('type', 'bank');
            $add = [];
            if ($apply_type == 'bank')
            {
                if(!$user_bank = UserBank::where('user_id', $userId)->find()){
                    if($no = Bank::whereLike('guard_name', $params['bank_name'])->value('no')){
                        $user_bank = UserBank::create([
                            'user_id'=>$userId,
                            'type'=>'bank',
                            'real_name'=>$params['real_name'],
                            'bank_name'=>$params['bank_name'],
                            'card_no'=>$params['card_no'],
                            'no'=>$no
                        ]);
                    }else{
                        return showError('银行选择有误');
                    }
                }else{
//                if($user_bank['status'] == 'disabled'){
//                    return showError('银行卡信息有误，请修改后再提现');
//                }
                    UserBank::where('user_id', $userId)->update([
                        'type'=>'bank',
                        'real_name'=>$params['real_name'],
                        'bank_name'=>$params['bank_name'],
                        'card_no'=>$params['card_no'],
                        'no'=>$user_bank['no'],
                        'status'=>'waiting'
                    ]);
                }
                $add['bank_account_name'] = $params['real_name'];
                $add['bank_card_no'] = $params['card_no'];
                $add['bank_name'] = $params['bank_name'];
            }elseif ($apply_type == 'alipay'){
                if(!$user_alipay = UserAlipay::where('user_id', $userId)->find()){
                    UserAlipay::create([
                        'user_id'=>$userId,
                        'account'=>$params['alipay_account'],
                        'real_name'=>$params['alipay_real_name'],
                    ]);
                }else{
                    UserAlipay::where('user_id', $userId)->update([
                        'account'=>$params['alipay_account'],
                        'real_name'=>$params['alipay_real_name'],
                    ]);
                }
                $add['alipay_account'] = $params['alipay_account'];
                $add['alipay_real_name'] = $params['alipay_real_name'];
            }

            $add['user_id'] = $userId;
            $add['apply_type'] = $apply_type;
            $add['apply_sn'] = 'M' . date('YmdHis');//.strtoupper(Str::random());
            $add['money'] = bcdiv_amount($amount);
            $add['need_money'] = bcdiv_amount($real_money);
            $add['charge_money'] = bcdiv_amount($rate_money);
            $add['service_fee'] = $rate;
//            $add['user_bank_id'] = $user_bank->id;
//            $add['apply_info'] = json_encode([
//                'bankAccountName'=>$params['real_name'],
//                'bankName'=>$params['bank_name'],
////                'branchName'=>$params['bank_name'],
//                'bankCard'=>$params['card_no'],
//            ], JSON_UNESCAPED_UNICODE);

            $type = 'score_withdrawals';
            $alias = 'score';
            $isDone = User::afterWithdrawals($userId, $real_money, $alias, $type, $add);
            if($isDone === true){
                return showSuccess([], '提现成功');
            }else{
                return showError('提现失败');
            }
        }else{
            return showError('不在提现时间内');
        }
    }

    public function logs(){
        if(request()->isPost()){
            $userId = request()->UserModel->id;
//            dd($userId);
//            $type = request()->param('type', 'income');
//            $where = $type == 'income' ? [['amount', '>', 0]] : [['amount', '<', 0]];
            $where = [];
            $where[] = ['id', '>', 0];
            $where[] = ['is_delete', '=', 0];
            $list = UserScoreLog::where($where)
                ->where('user_id', $userId)
                ->where('is_delete', 0)
                ->append(['amount_format', 'icon'])
                ->order('create_time DESC')
                ->paginate($this->pageSize)
                ->toArray();
            $data = [];
            $data['total_page'] = (int)ceil($list['total']/$this->pageSize);;
            $data['page_size'] = $this->pageSize;
            $data['page'] = $list['current_page'];
            $data['lists'] = $list['data'];

            return showSuccess($data);
        }else{
            $data = [
                'main_title'=>'账单记录',
                'background'=>'',
                'title'=>'',
                'amount'=>0,
                'tip'=>'',
                'safe'=>[
                    'enable'=>false,
                    'img'=>'',
                    'text'=>'',
                ],
                'lists'=>[
                    'enable'=>true,
                    'img'=>'',
                    'formData'=>[],
                ],

            ];
            $data['page_size'] = $this->pageSize;
            $data['page'] = 1;
            return showSuccess($data);
        }
    }
}